package com.ruoyi.robot.Interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ruoyi.robot.pojo.po.Customer;
import com.ruoyi.robot.util.BaseUserInfo;
import com.ruoyi.robot.util.JWTUtils;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author admin
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = request.getHeader("Authorization");

        try {
            JWTUtils.verify(token);
        }catch (SignatureVerificationException e) {
            log.error("无效签名！ 错误 ->", e);
            throw new SignatureException("无效签名！", e);
        } catch (TokenExpiredException e) {
            log.error("token过期！ 错误 ->", e);
            throw new SignatureException("token过期！", e);
        } catch (AlgorithmMismatchException e) {
            log.error("token算法不一致！ 错误 ->", e);
            throw new SignatureException("token算法不一致！", e);
        } catch (Exception e) {
            log.error("token无效！ 错误 ->", e);
            throw new SignatureException("token无效！", e);
        }

        //根据token解析数据，因为配置了全局异常处理中心，如果有异常会在全局异常中心处理异常
        DecodedJWT tokenInfo = JWTUtils.verify(token);
        //获得用户信息
        String customerAccount = tokenInfo.getClaim("customerAccount").asString();
        String customerName = tokenInfo.getClaim("customerName").asString();
        String customerPhone = tokenInfo.getClaim("customerPhone").asString();
        String customerEmail = tokenInfo.getClaim("customerEmail").asString();
        String avatar = tokenInfo.getClaim("avatar").asString();
        String customerId = tokenInfo.getClaim("customerId").asString();
        //存储用户信息到ThreadLocal中
        Customer customer = new Customer();
        customer.setCustomerAccount(customerAccount);
        customer.setCustomerName(customerName);
        customer.setCustomerPhone(customerPhone);
        customer.setCustomerEmail(customerEmail);
        customer.setAvatar(avatar);
        customer.setCustomerId(Long.valueOf(customerId));
        BaseUserInfo.set("customer",customer);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseUserInfo.remove();
    }
}
